import request from '@/router/axios'
import website from '@/config/website'
import { getSosWay } from '@/util/auth'

const getGrantType = () => {
  // 两种模式:普通的用户名密码登录；逃生通道登录方式
  if (process.env.VUE_APP_TYPE === 'boot') {
    return website.captchaMode ? 'captcha' : 'password'
  }
  return 'sos_way'
}
export const loginByUsername = (tenantId, username, pValue, type, key, code) => request({
  url: '/yitu-auth/oauth/token',
  method: 'post',
  headers: {
    'Tenant-Id': tenantId,
    'Captcha-Key': key,
    'Captcha-Code': code
  },
  params: {
    tenantId,
    username,
    pValue,
    grant_type: getGrantType(),
    scope: 'all',
    type
  }
})

const getRefreshTokenUrl = () => {
  return (process.env.VUE_APP_TYPE === 'boot' || getSosWay() === true) ? '/yitu-auth/oauth/token' : '/yitu-service-auth-api/oauth2/refreshToken'
}

export const refreshToken = (refresh_token, tenantId) => {
  // 使用底座调用yitu-auth/oauth/token
  // 使用基于底座业务系统登录刷新使用/yitu-service-auth-api/oauth2/refreshToken
  const url = getRefreshTokenUrl()
  return request({
    url,
    method: 'post',
    headers: {
      'Tenant-Id': tenantId
    },
    params: {
      tenantId,
      refresh_token,
      grant_type: 'refresh_token',
      scope: 'all'
    }
  })
}

export const getButtons = () => request({
  url: '/yitu-system/menu/buttons',
  method: 'get'
})

export const getCaptcha = () => request({
  url: '/yitu-auth/oauth/captcha',
  method: 'get'
})

export const logout = () => request({
  url: '/backend/login/logout',
  method: 'get'
})

export const getUserInfo = () => request({
  url: '/yitu-auth/oauth/user-info',
  method: 'get'
})

export const sendLogs = (list) => request({
  url: '/yitu-auth/oauth/logout',
  method: 'post',
  data: list
})

export const clearCache = () => request({
  url: '/yitu-auth/oauth/clear-cache',
  method: 'get'
})
/**
 * 获取授权接口
 * @param {*} code
 * @returns
 */
export const getTokenlogin = (code) => {
  return request({
    url: '/yitu-service-auth-api/oauth2/login',
    method: 'post',
    params: { code }
  })
}
/**
 * 获取yitu:token对应的配置
 */
export const tokenConfig = () => {
  return request({
    url: '/yitu-auth/oauth/tokenConfig',
    method: 'get'
  })
}
/**
 * 用于调用鉴权接口
 */

export const sosWay = () => {
  return request({
    url: '/yitu-system/public/sosWay',
    method: 'post'
  })
}
